#include "AsioIOServicePool.h"
#include <iostream>

AsioIOServicePool::~AsioIOServicePool()
{
    Stop();
    std::cout<<"AsioIOServicePool::~AsioIOServicePool()\n";
}


boost::asio::io_context& AsioIOServicePool::GetIOService()
{
    auto& io_context = io_contexts_[nextIOService_++];
    if(nextIOService_>=io_contexts_.size())
    {
        nextIOService_ = 0;
    }
    return io_context;
}


AsioIOServicePool::AsioIOServicePool(std::size_t threadNum)
:nextIOService_(0),io_contexts_(threadNum)
{
    works_.reserve(threadNum);
    threads_.reserve(threadNum);
    for(int i=0;i<threadNum;++i)
    {
        works_.emplace_back(std::make_unique<Work>(io_contexts_[i]));
        threads_.emplace_back([this,i](){
            io_contexts_[i].run();
        });
    }
}

void AsioIOServicePool::Stop()
{

    works_.clear();
    for(auto& io_context:io_contexts_)
    {
        io_context.stop();
    }
    //回收线程
    for(auto& thread:threads_)
    {
        thread.join();
    }
}
